import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: 冯若航
 * \* Date: 2021/6/4
 * \* Time: 12:36
 * \* To change this template use File | Settings | File Templates.
 * \* Description:
 * \
 */
public class 寻找重复的子树 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    HashMap<String, Integer> memo=new HashMap<>();
    LinkedList<TreeNode> res=new LinkedList<>();
    public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
        traverse(root);
        return res;
    }

    String traverse(TreeNode root){
        if(root==null){
            return "#";
        }

        String left=traverse(root.left);
        String right=traverse(root.right);

        String subTree=left+","+right+","+root.val;
        int freq=memo.getOrDefault(subTree,0);
        //多次重复也只会也如结果集一次
        if(freq==1){
            res.add(root);
        }
        //给字数对应的出现次数加一
        memo.put(subTree,freq+1);
        return subTree;
    }
}